import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Card,
  Typography,
  Button,
  TextField,
  CircularProgress,
  Avatar,
  Chip,
  Alert,
  Box,
  Divider
} from '@mui/material';
import {
  CheckCircle,
  Cancel,
  Error as ErrorIcon,
  Person,
  Email,
  CalendarToday,
  AdminPanelSettings
} from '@mui/icons-material';
import { useUser } from '../../hooks/useUser';
import { User } from '../../types';
import styles from './AdminReview.module.css';

const AdminReview: React.FC = () => {
  const { userId } = useParams<{ userId: string }>();
  const navigate = useNavigate();
  const { loading, error, getUserById, reviewAdminApplication } = useUser();
  
  const [user, setUser] = useState<User | null>(null);
  const [showRejectReason, setShowRejectReason] = useState(false);
  const [rejectReason, setRejectReason] = useState('');
  const [reviewStatus, setReviewStatus] = useState<'pending' | 'success' | 'error'>('pending');
  const [reviewMessage, setReviewMessage] = useState('');
  const [submitting, setSubmitting] = useState(false);

  // 加载用户信息
  useEffect(() => {
    if (userId) {
      loadUserInfo();
    }
  }, [userId]);

  const loadUserInfo = async () => {
    try {
      const userData = await getUserById(Number(userId));
      setUser(userData as User);
    } catch (err) {
      console.error('加载用户信息失败:', err);
    }
  };

  // 处理审核通过
  const handleApprove = async () => {
    if (!userId) return;
    
    setSubmitting(true);
    try {
      await reviewAdminApplication(Number(userId), { approved: true });
      setReviewStatus('success');
      setReviewMessage('管理员申请已通过审核');
    } catch (err) {
      setReviewStatus('error');
      setReviewMessage('审核操作失败，请稍后重试');
      console.error('审核失败:', err);
    } finally {
      setSubmitting(false);
    }
  };

  // 处理审核拒绝
  const handleReject = async () => {
    if (!userId || !rejectReason.trim()) {
      alert('请填写拒绝原因');
      return;
    }
    
    setSubmitting(true);
    try {
      await reviewAdminApplication(Number(userId), {
        approved: false,
        rejectReason: rejectReason.trim()
      });
      setReviewStatus('success');
      setReviewMessage('管理员申请已拒绝');
    } catch (err) {
      setReviewStatus('error');
      setReviewMessage('审核操作失败，请稍后重试');
      console.error('审核失败:', err);
    } finally {
      setSubmitting(false);
    }
  };

  // 格式化日期
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 获取角色显示文本
  const getRoleText = (role: string) => {
    const roleMap = {
      'USER': '普通用户',
      'ADMIN': '管理员',
      'SUPERADMIN': '超级管理员'
    };
    return roleMap[role as keyof typeof roleMap] || role;
  };

  // 获取角色颜色
  const getRoleColor = (role: string) => {
    const colorMap = {
      'USER': 'default',
      'ADMIN': 'primary',
      'SUPERADMIN': 'secondary'
    };
    return colorMap[role as keyof typeof colorMap] || 'default';
  };

  if (!userId) {
    return (
      <div className={styles.container}>
        <Card className={styles.reviewCard}>
          <div className={styles.errorContainer}>
            <ErrorIcon className={styles.errorIcon} />
            <Typography variant="h5" className={styles.errorTitle}>
              参数错误
            </Typography>
            <Typography variant="body1" className={styles.errorMessage}>
              未提供有效的用户ID
            </Typography>
            <Box sx={{ display: 'flex', gap: 2, justifyContent: 'center', mt: 3 }}>
              <Button
                variant="outlined"
                onClick={() => navigate('/admin/applications')}
                className={styles.backButton}
              >
                返回申请列表
              </Button>
              <Button
                variant="contained"
                onClick={() => navigate('/home')}
                className={styles.backButton}
              >
                返回首页
              </Button>
            </Box>
          </div>
        </Card>
      </div>
    );
  }

  if (loading) {
    return (
      <div className={styles.container}>
        <Card className={styles.reviewCard}>
          <div className={styles.loadingContainer}>
            <CircularProgress size={60} />
            <Typography variant="body1">
              正在加载用户信息...
            </Typography>
          </div>
        </Card>
      </div>
    );
  }

  if (error || !user) {
    return (
      <div className={styles.container}>
        <Card className={styles.reviewCard}>
          <div className={styles.errorContainer}>
            <ErrorIcon className={styles.errorIcon} />
            <Typography variant="h5" className={styles.errorTitle}>
              加载失败
            </Typography>
            <Typography variant="body1" className={styles.errorMessage}>
              {error || '无法获取用户信息'}
            </Typography>
            <Box sx={{ display: 'flex', gap: 2, justifyContent: 'center', mt: 3 }}>
              <Button
                variant="outlined"
                onClick={loadUserInfo}
                className={styles.backButton}
              >
                重新加载
              </Button>
              <Button
                variant="outlined"
                onClick={() => navigate('/admin/applications')}
                className={styles.backButton}
              >
                返回申请列表
              </Button>
              <Button
                variant="contained"
                onClick={() => navigate('/home')}
                className={styles.backButton}
              >
                返回首页
              </Button>
            </Box>
          </div>
        </Card>
      </div>
    );
  }

  if (reviewStatus === 'success') {
    return (
      <div className={styles.container}>
        <Card className={styles.reviewCard}>
          <div className={styles.successContainer}>
            <CheckCircle className={styles.successIcon} />
            <Typography variant="h4" className={styles.successTitle}>
              审核完成
            </Typography>
            <Typography variant="body1" className={styles.successMessage}>
              {reviewMessage}
            </Typography>
            <Box sx={{ display: 'flex', gap: 2, justifyContent: 'center', mt: 3 }}>
              <Button
                variant="outlined"
                onClick={() => navigate('/admin/applications')}
                className={styles.backButton}
              >
                返回申请列表
              </Button>
              <Button
                variant="contained"
                onClick={() => navigate('/home')}
                className={styles.backButton}
              >
                返回首页
              </Button>
            </Box>
          </div>
        </Card>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      <Card className={styles.reviewCard}>
        {/* 页面标题 */}
        <div className={styles.header}>
          <Typography variant="h4" className={styles.title}>
            管理员申请审核
          </Typography>
          <Typography variant="body1" className={styles.subtitle}>
            请仔细审查申请人信息，做出审核决定
          </Typography>
        </div>

        {/* 用户信息卡片 */}
        <div className={styles.userInfo}>
          <div className={styles.userHeader}>
            <Avatar
              src={user.avatar}
              alt={user.username}
              className={styles.avatar}
            >
              <Person />
            </Avatar>
            <div className={styles.userDetails}>
              <h3>{user.username}</h3>
              <p>{user.email}</p>
            </div>
          </div>

          <Divider sx={{ my: 2 }} />

          <div className={styles.infoGrid}>
            <div className={styles.infoItem}>
              <Typography variant="caption" className={styles.infoLabel}>
                <Person sx={{ fontSize: 14, mr: 0.5 }} />
                用户名
              </Typography>
              <Typography variant="body2" className={styles.infoValue}>
                {user.username}
              </Typography>
            </div>

            <div className={styles.infoItem}>
              <Typography variant="caption" className={styles.infoLabel}>
                <Email sx={{ fontSize: 14, mr: 0.5 }} />
                邮箱地址
              </Typography>
              <Typography variant="body2" className={styles.infoValue}>
                {user.email}
              </Typography>
            </div>

            <div className={styles.infoItem}>
              <Typography variant="caption" className={styles.infoLabel}>
                <AdminPanelSettings sx={{ fontSize: 14, mr: 0.5 }} />
                申请角色
              </Typography>
              <Chip
                label={getRoleText(user.role)}
                color={getRoleColor(user.role) as any}
                size="small"
              />
            </div>

            <div className={styles.infoItem}>
              <Typography variant="caption" className={styles.infoLabel}>
                <CalendarToday sx={{ fontSize: 14, mr: 0.5 }} />
                申请时间
              </Typography>
              <Typography variant="body2" className={styles.infoValue}>
                {formatDate(user.createdAt)}
              </Typography>
            </div>

            {user.bio && (
              <div className={styles.infoItem} style={{ gridColumn: '1 / -1' }}>
                <Typography variant="caption" className={styles.infoLabel}>
                  个人简介
                </Typography>
                <Typography variant="body2" className={styles.infoValue}>
                  {user.bio}
                </Typography>
              </div>
            )}
          </div>
        </div>

        {/* 错误提示 */}
        {reviewStatus === 'error' && (
          <Alert severity="error" sx={{ mb: 3 }}>
            {reviewMessage}
          </Alert>
        )}

        {/* 审核操作 */}
        <div className={styles.actionSection}>
          <div className={styles.buttonGroup}>
            <Button
              variant="contained"
              onClick={handleApprove}
              disabled={submitting}
              className={styles.approveButton}
              startIcon={submitting ? <CircularProgress size={16} /> : <CheckCircle />}
            >
              {submitting ? '处理中...' : '通过申请'}
            </Button>

            <Button
              variant="contained"
              onClick={() => setShowRejectReason(!showRejectReason)}
              disabled={submitting}
              className={styles.rejectButton}
              startIcon={<Cancel />}
            >
              拒绝申请
            </Button>
          </div>

          {/* 拒绝原因输入框 */}
          {showRejectReason && (
            <div className={styles.rejectReasonField}>
              <TextField
                fullWidth
                multiline
                rows={4}
                label="拒绝原因"
                placeholder="请详细说明拒绝申请的原因..."
                value={rejectReason}
                onChange={(e) => setRejectReason(e.target.value)}
                variant="outlined"
                required
                helperText="请提供详细的拒绝原因，以便申请人了解情况"
              />
              <Box sx={{ mt: 2, display: 'flex', gap: 2, justifyContent: 'flex-end' }}>
                <Button
                  variant="outlined"
                  onClick={() => {
                    setShowRejectReason(false);
                    setRejectReason('');
                  }}
                  disabled={submitting}
                >
                  取消
                </Button>
                <Button
                  variant="contained"
                  onClick={handleReject}
                  disabled={submitting || !rejectReason.trim()}
                  className={styles.rejectButton}
                  startIcon={submitting ? <CircularProgress size={16} /> : <Cancel />}
                >
                  {submitting ? '处理中...' : '确认拒绝'}
                </Button>
              </Box>
            </div>
          )}
        </div>
      </Card>
    </div>
  );
};

export default AdminReview; 